package com.bjtu.lms.action.borrow;

import com.bjtu.lms.model.Book;
import com.bjtu.lms.model.BorrowHistory;
import com.bjtu.lms.model.User;
import com.bjtu.lms.service.BookService;
import com.bjtu.lms.service.BorrowHistoryService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * @author yilee
 */
public class HistoryBorrowAction extends ActionSupport {

	private BookService bookService;
	private BorrowHistoryService borrowHistoryService;

	public BorrowHistoryService getBorrowHistoryService() {
		return borrowHistoryService;
	}

	public void setBorrowHistoryService(BorrowHistoryService borrowHistoryService) {
		this.borrowHistoryService = borrowHistoryService;
	}

	public BookService getBookService() {
		return bookService;
	}

	public void setBookService(BookService bookService) {
		this.bookService = bookService;
	}

	@Override
	public String execute() throws Exception {
		ActionContext actionContext = ActionContext.getContext();
		Map session = actionContext.getSession();
		User u = (User) session.get("user");
		if (u != null) {
			List<Book> bookList = null;
			List<BorrowHistory> borrowHistoryList = borrowHistoryService.getBorrowHistoryListByUserId(u.getId());

			Book b = null;
			BorrowHistory borrowHistory = null;
			if (borrowHistoryList != null) {
				bookList = new ArrayList<Book>();
				for (int i = 0; i < borrowHistoryList.size(); i++) {
					borrowHistory = borrowHistoryList.get(i);
					b = bookService.findBooksById(borrowHistory.getBookId());
					b.setBorrowDate(borrowHistory.getBorrowDate());
					b.setReturnDate(borrowHistory.getReturnDate());
					b.setReBorrowTimes(borrowHistory.getReBorrowTimes());
					bookList.add(b);
				}
				session.put("bookList", bookList);
			} else {
				session.put("bookList", null);
			}
		}
		return SUCCESS;
	}
}
